﻿
Imports VSModel
Imports Cls_Common
Imports System.IO

Partial Class Control_Reports_DiaPhuongNganhNghe
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Dim level As String = -1

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "regjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "regjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            hidCurProvince.Value = Session("HuyenId")
            LoadData()
        End If
    End Sub
    Private Sub LoadData()
        Using _data As New VSEntities

        
            'phuong xa
            Dim phuongxa = (From q In _data.Provinces Where q.Id = hidCurProvince.Value Select q).FirstOrDefault
            'With ddlDiaPhuong
            '    '.DataSource = phuongxa
            '    .DataValueField = "Id"
            '    .DataTextField = "Title"
            '    '' .DataBind()
            'End With
            If phuongxa Is Nothing Then
                RecursiveFillTree(171)
            Else

                RecursiveFillTree(phuongxa.Id)
            End If

            '  ddlDiaPhuong.Items.Insert(0, New ListItem("--- Tất cả ---", "0"))

        End Using
    End Sub
    Private Sub RecursiveFillTree(ByVal parentID As Integer)
        level += 1
        'on the each call level increment 1
        Dim appender As New StringBuilder()

        For j As Integer = 0 To level - 1
            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;")
        Next
        If level > 0 Then
            appender.Append("|__")
        End If

        Dim data As New VSEntities
        Dim dv As List(Of Province) = (From q In data.Provinces Where q.ParentId = parentID Select q Order By q.Title).ToList
        Dim i As Integer

        If dv.Count > 0 Then
            For i = 0 To dv.Count - 1
                Dim itm As New ListItem(Server.HtmlDecode(appender.ToString() + dv.Item(i).Title.ToString()), dv.Item(i).Id.ToString())
                ddlDiaPhuong.Items.Add(itm)
                RecursiveFillTree(Integer.Parse(dv.Item(i).Id.ToString()))
            Next
        End If

        level -= 1
        'on the each function end level will decrement by 1
    End Sub
#Region "Sub and Function"
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1, _
                           Optional ByVal strDiaPhuong As String = "", _
                           Optional ByVal dateFrom As DateTime = #1/1/1900#, _
                           Optional ByVal dateTo As DateTime = #12/31/3999#, _
                           Optional ByVal strLinhVuc As String = "")
        If dateTo = #1/1/1900# Then
            dateTo = #12/31/3999#
        End If

        Using data As New VSEntities
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            Dim arrSearch() As String = {iPage.ToString, strDiaPhuong, dateFrom.ToString(), dateTo.ToString(), strLinhVuc}
            ViewState("search") = arrSearch
            Dim p = data.uspCertifiedHouseholdReportByDPhuongNN(strDiaPhuong, dateFrom, dateTo, strLinhVuc, hidCurProvince.Value, iPage, intPag_Size).ToList()
            'Tong so ban ghi
            If p.Count > 0 Then
                hidCount.Value = p.FirstOrDefault().Total
                btnExportToExcel.Visible = True
            Else
                hidCount.Value = 0
                btnExportToExcel.Visible = False
            End If

            Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            With grdShow
                '.DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)

        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(lnkTile.ToolTip, arrSearch(1), arrSearch(2), arrSearch(3), arrSearch(4))

        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(hidCur_Page.Value, arrSearch(1), arrSearch(2), arrSearch(3), arrSearch(4))
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(hidCur_Page.Value, arrSearch(1), arrSearch(2), arrSearch(3), arrSearch(4))
    End Sub


    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1), arrSearch(2), arrSearch(3), arrSearch(4))
    End Sub
#End Region

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSearch.Click
        Dim _diaPhuong As String = ""
        For Each i In ddlDiaPhuong.GetSelectedIndices()

            _diaPhuong = _diaPhuong & "," & ddlDiaPhuong.Items(i).Value

        Next

        BindToGrid(1, _diaPhuong, StringToDate(txtCertifieddateFrom.Text), StringToDate(txtCertifieddateTo.Text), txtNgayNgheKinhDoanh.Text)

    End Sub
    Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click
        ddlDiaPhuong.SelectedIndex = -1
        txtNgayNgheKinhDoanh.Text = ""
        txtCertifieddateTo.Text = ""
        txtCertifieddateFrom.Text = ""
    End Sub
    Protected Sub btnExportToExcel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnExportToExcel.Click
        Try
            Dim arrSearch() As String
            Dim _fieldName As String() = {"RowNum", "CertifiedCode", "CertifiedDate", "Biz_VietName", "Ow_Name", "Ow_Sex", "Ow_BirthDate", "Ow_CardID", "DiaPhuong", "Biz_HeadOffice", "LinhVucKinhDoanh", "Biz_InvestCapital"}
            arrSearch = ViewState("search")
            Using data As New VSEntities
                Dim _fileName As String = "ReportDiaPhuong_" & Date.Now.ToFileTimeUtc()
                Dim p = data.uspCertifiedHouseholdReportByDPhuongNN(arrSearch(1), arrSearch(2), arrSearch(3), arrSearch(4), hidCurProvince.Value, 0, 0).ToList
                Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
                If Not applicationPath.EndsWith("\") Then
                    applicationPath = applicationPath + "\"
                End If
                Dim licenseFile As String = Path.Combine(applicationPath, "bin\Aspose.Cells.lic")
                Dim license As Aspose.Cells.License = New Aspose.Cells.License()
                license.SetLicense(licenseFile)
                Dim _workbook As New Aspose.Cells.Workbook(Server.MapPath("~/Template/ReportDiaPhuong.xls"))
                Dim _workSheet As Aspose.Cells.Worksheet = _workbook.Worksheets(0)
                _workSheet.Cells.ImportCustomObjects(CType(p, System.Collections.ICollection), _fieldName, False, 6, 0, p.Count, True, "dd/MM/yyyy", False)
                _workSheet.AutoFitColumns()
                Cls_Common.CreateDir(Server.MapPath("~/Template/ReportDownload/"))
                _workbook.Save(Server.MapPath("~/Template/ReportDownload/" & _fileName & ".xls"))

                Excute_Javascript("Alertbox('Xuất dữ liệu thành công'); SetDownFile('" & ResolveUrl("~/Template/ReportDownload/" & _fileName & ".xls") & "')", Me.Page, True)


            End Using
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()
            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Xuất dữ liệu thất bại." & ex.Message & "');", Me.Page, True)
        End Try

    End Sub
    Protected Sub hplSelectNganhNghe_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplSelectNganhNghe.Init
        hplSelectNganhNghe.NavigateUrl = "~/FrontEnd/Page/Member/Popup.aspx?keepThis=true&TB_iframe=true&height=420&width=500&modal=true"
        hplSelectNganhNghe.CssClass = "thickbox"

    End Sub
End Class
